<template>
  <div class="todo-notes">
    <div class="header">
      <h1>待办事项</h1>
      <router-link to="/editor/todo" class="btn btn-primary">
        <span class="icon">+</span>
        新建待办
      </router-link>
    </div>
    
    <div class="filters">
      <input 
        v-model="searchQuery" 
        type="text" 
        placeholder="搜索待办事项..." 
        class="input search-input"
      />
      <select v-model="selectedCategory" class="input">
        <option value="">所有分类</option>
        <option v-for="category in categories" :key="category.id" :value="category.id">
          {{ category.name }}
        </option>
      </select>
      <select v-model="selectedStatus" class="input">
        <option value="">所有状态</option>
        <option value="pending">待处理</option>
        <option value="in_progress">进行中</option>
        <option value="completed">已完成</option>
      </select>
    </div>
    
    <div class="todo-lists">
      <div 
        v-for="note in filteredNotes" 
        :key="note.id" 
        class="todo-card"
      >
        <div class="todo-header">
          <h3>{{ note.title }}</h3>
          <div class="todo-actions">
            <button @click="editNote(note)" class="btn">编辑</button>
            <button @click="deleteNote(note.id)" class="btn btn-danger">删除</button>
          </div>
        </div>
        
        <div class="todo-stats">
          <span class="stat">
            总计: {{ note.todos.length }}
          </span>
          <span class="stat">
            已完成: {{ getCompletedCount(note.todos) }}
          </span>
          <span class="stat">
            进行中: {{ getInProgressCount(note.todos) }}
          </span>
        </div>
        
        <div class="todo-items">
          <div 
            v-for="todo in getFilteredTodos(note.todos)" 
            :key="todo.id" 
            class="todo-item"
            :class="{ completed: todo.status === 'completed' }"
          >
            <div class="todo-content">
              <input 
                type="checkbox" 
                :checked="todo.status === 'completed'"
                @change="toggleTodoStatus(note.id, todo.id)"
                class="todo-checkbox"
              />
              <div class="todo-info">
                <h4>{{ todo.title }}</h4>
                <p v-if="todo.description">{{ todo.description }}</p>
                <div class="todo-meta">
                  <span class="priority" :class="todo.priority">{{ getPriorityText(todo.priority) }}</span>
                  <span v-if="todo.dueDate" class="due-date">{{ formatDate(todo.dueDate) }}</span>
                  <span class="category">{{ getCategoryName(todo.category) }}</span>
                </div>
              </div>
            </div>
            <div class="todo-item-actions">
              <button @click="editTodoItem(note.id, todo)" class="btn btn-small">编辑</button>
              <button @click="deleteTodoItem(note.id, todo.id)" class="btn btn-small btn-danger">删除</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="filteredNotes.length === 0" class="empty-state">
      <p>暂无待办事项</p>
      <router-link to="/editor/todo" class="btn btn-primary">创建第一个待办事项</router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useNoteStore } from '@/stores/noteStore';
import { formatDate } from '@/utils/helpers';
import { TodoStatus } from '@/types';
import type { TodoNote, TodoItem } from '@/types';

const router = useRouter();
const noteStore = useNoteStore();

const searchQuery = ref('');
const selectedCategory = ref('');
const selectedStatus = ref('');

const categories = computed(() => noteStore.categories);
const todoNotes = computed(() => noteStore.todoNotes as TodoNote[]);

const filteredNotes = computed(() => {
  let notes = todoNotes.value;
  
  if (searchQuery.value) {
    notes = notes.filter(note => 
      note.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      note.todos.some(todo => 
        todo.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        todo.description?.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    );
  }
  
  if (selectedCategory.value) {
    notes = notes.filter(note => 
      note.todos.some(todo => todo.category === selectedCategory.value)
    );
  }
  
  return notes.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
});

const getFilteredTodos = (todos: TodoItem[]) => {
  let filtered = todos;
  
  if (selectedStatus.value) {
    filtered = filtered.filter(todo => todo.status === selectedStatus.value);
  }
  
  if (selectedCategory.value) {
    filtered = filtered.filter(todo => todo.category === selectedCategory.value);
  }
  
  return filtered.sort((a, b) => {
    // 按优先级和创建时间排序
    const priorityOrder = { high: 3, medium: 2, low: 1 };
    const aPriority = priorityOrder[a.priority as keyof typeof priorityOrder] || 1;
    const bPriority = priorityOrder[b.priority as keyof typeof priorityOrder] || 1;
    
    if (aPriority !== bPriority) {
      return bPriority - aPriority;
    }
    
    return b.createdAt.getTime() - a.createdAt.getTime();
  });
};

const getCompletedCount = (todos: TodoItem[]) => {
  return todos.filter(todo => todo.status === TodoStatus.COMPLETED).length;
};

const getInProgressCount = (todos: TodoItem[]) => {
  return todos.filter(todo => todo.status === TodoStatus.IN_PROGRESS).length;
};

const editNote = (note: TodoNote) => {
  router.push(`/editor/todo/${note.id}`);
};

const deleteNote = (id: string) => {
  if (confirm('确定要删除这个待办事项吗？')) {
    noteStore.deleteNote(id);
  }
};

const toggleTodoStatus = (noteId: string, todoId: string) => {
  const note = todoNotes.value.find(n => n.id === noteId);
  if (note) {
    const todo = note.todos.find(t => t.id === todoId);
    if (todo) {
      const newStatus = todo.status === TodoStatus.COMPLETED 
        ? TodoStatus.PENDING 
        : TodoStatus.COMPLETED;
      noteStore.updateTodoItem(noteId, todoId, { status: newStatus });
    }
  }
};

const editTodoItem = (noteId: string, todo: TodoItem) => {
  // 这里可以实现编辑待办事项的逻辑
  console.log('编辑待办事项:', todo);
};

const deleteTodoItem = (noteId: string, todoId: string) => {
  if (confirm('确定要删除这个待办事项吗？')) {
    noteStore.deleteTodoItem(noteId, todoId);
  }
};

const getPriorityText = (priority: string): string => {
  const priorityMap: Record<string, string> = {
    high: '高',
    medium: '中',
    low: '低'
  };
  return priorityMap[priority] || '中';
};

const getCategoryName = (categoryId: string): string => {
  const category = categories.value.find(c => c.id === categoryId);
  return category?.name || '未分类';
};
</script>

<style lang="scss" scoped>
.todo-notes {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    
    h1 {
      font-size: $font-size-xxl;
      color: $primary-color;
    }
    
    .btn {
      display: flex;
      align-items: center;
      gap: $spacing-xs;
      
      .icon {
        font-size: $font-size-large;
      }
    }
  }
  
  .filters {
    display: flex;
    gap: $spacing-md;
    margin-bottom: $spacing-lg;
    
    .search-input {
      flex: 1;
    }
    
    select {
      min-width: 150px;
    }
  }
  
  .todo-lists {
    display: flex;
    flex-direction: column;
    gap: $spacing-lg;
    
    .todo-card {
      background-color: $secondary-color;
      border: $border-width solid $border-color;
      border-radius: $border-radius;
      padding: $spacing-lg;
      
      .todo-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: $spacing-md;
        
        h3 {
          font-size: $font-size-xl;
          color: $primary-color;
          margin: 0;
        }
        
        .todo-actions {
          display: flex;
          gap: $spacing-sm;
        }
      }
      
      .todo-stats {
        display: flex;
        gap: $spacing-lg;
        margin-bottom: $spacing-md;
        padding: $spacing-sm;
        background-color: $hover-color;
        border-radius: $border-radius;
        
        .stat {
          color: $text-light;
          font-size: $font-size-small;
        }
      }
      
      .todo-items {
        display: flex;
        flex-direction: column;
        gap: $spacing-sm;
        
        .todo-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding: $spacing-md;
          border: $border-width solid $border-color;
          border-radius: $border-radius;
          background-color: $secondary-color;
          
          &.completed {
            opacity: 0.6;
            
            .todo-content h4 {
              text-decoration: line-through;
            }
          }
          
          .todo-content {
            display: flex;
            align-items: flex-start;
            gap: $spacing-sm;
            flex: 1;
            
            .todo-checkbox {
              margin-top: 4px;
            }
            
            .todo-info {
              flex: 1;
              
              h4 {
                font-size: $font-size-base;
                color: $text-color;
                margin: 0 0 $spacing-xs 0;
              }
              
              p {
                color: $text-light;
                font-size: $font-size-small;
                margin: 0 0 $spacing-xs 0;
                line-height: 1.4;
              }
              
              .todo-meta {
                display: flex;
                gap: $spacing-sm;
                flex-wrap: wrap;
                
                .priority {
                  padding: 2px $spacing-xs;
                  border-radius: 2px;
                  font-size: $font-size-small;
                  
                  &.high {
                    background-color: #ff4757;
                    color: $secondary-color;
                  }
                  
                  &.medium {
                    background-color: #ffa502;
                    color: $secondary-color;
                  }
                  
                  &.low {
                    background-color: #2ed573;
                    color: $secondary-color;
                  }
                }
                
                .due-date, .category {
                  background-color: $hover-color;
                  color: $text-color;
                  padding: 2px $spacing-xs;
                  border-radius: 2px;
                  font-size: $font-size-small;
                }
              }
            }
          }
          
          .todo-item-actions {
            display: flex;
            gap: $spacing-xs;
            
            .btn-small {
              padding: $spacing-xs $spacing-sm;
              font-size: $font-size-small;
            }
          }
        }
      }
    }
  }
  
  .empty-state {
    text-align: center;
    padding: $spacing-xl 0;
    color: $text-light;
    
    p {
      margin-bottom: $spacing-lg;
      font-size: $font-size-large;
    }
  }
  
  @media (max-width: $breakpoint-mobile) {
    .header {
      flex-direction: column;
      gap: $spacing-md;
      align-items: stretch;
      
      .btn {
        justify-content: center;
      }
    }
    
    .filters {
      flex-direction: column;
    }
    
    .todo-card {
      .todo-header {
        flex-direction: column;
        gap: $spacing-md;
        align-items: stretch;
        
        .todo-actions {
          justify-content: flex-end;
        }
      }
      
      .todo-stats {
        flex-direction: column;
        gap: $spacing-xs;
      }
      
      .todo-items {
        .todo-item {
          flex-direction: column;
          gap: $spacing-sm;
          
          .todo-item-actions {
            align-self: flex-end;
          }
        }
      }
    }
  }
}
</style> 